package org.opens.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * 功能描述
 *
 * @author: zhangyuming
 * @date: 2023/7/7 10:42
 */
@Component
@Slf4j
@ServerEndpoint(value = "/telnet/websocket/{userId}/{serverId}")
public class TelnetWebsocket {

    /**
     * 新建连接
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId, @PathParam(value = "serverId") String serverId) {
        log.info("onOpen: {}, {}", userId, serverId);
        WebsocketManager.newSession(userId, session);
    }

    /**
     * websocket发送消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam(value = "userId") String userId, @PathParam(value = "serverId") String serverId) throws IOException {
        log.info("onMessage: {}, {}, {}", userId, serverId, message);
        WebsocketManager.telnetClientHolderMap.get(userId).sendCommand(message);
    }

    @OnClose
    public void onClose(@PathParam("userId") String userId) {
        log.info("onClose: {}", userId);
        WebsocketManager.closeSession(userId);
    }

    @OnError
    public void onError(Throwable throwable, @PathParam("userId") String userId) {
        log.info("onClose: {}", throwable.getMessage());
        WebsocketManager.closeSession(userId);
    }

}
